import { NextResponse } from 'next/server';
import prisma from '@/app/lib/prisma';
import { comparePasswords, generateToken } from '@/app/lib/auth';

export async function POST(request: Request) {
  try {
    const { email, password } = await request.json();

    const user = await prisma.user.findUnique({
      where: { email },
    });

    if (!user) {
      return NextResponse.json(
        { message: '邮箱或密码错误' },
        { status: 401 }
      );
    }

    const isValidPassword = await comparePasswords(password, user.password);
    if (!isValidPassword) {
      return NextResponse.json(
        { message: '邮箱或密码错误' },
        { status: 401 }
      );
    }

    // 生成JWT令牌
    const token = generateToken(user.id);

    // 创建响应
    const response = NextResponse.json(
      { 
        message: '登录成功',
        user: {
          id: user.id,
          email: user.email,
          name: user.name
        }
      },
      { status: 200 }
    );

    // 设置cookie
    response.cookies.set({
      name: 'auth-token',
      value: token,
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      path: '/',
      maxAge: 7 * 24 * 60 * 60, // 7天
    });

    // 在响应头中添加调试信息
    response.headers.set('Set-Cookie-Debug', 'auth-token cookie set');

    return response;
  } catch (error) {
    console.error('登录错误:', error);
    return NextResponse.json(
      { message: '登录失败，请稍后重试' },
      { status: 500 }
    );
  }
} 